#include "../include/muduo/net/TcpClient.h"
#include "../include/muduo/net/EventLoopThread.h"
#include "../include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>

class TranslateClient
{
public:
    TranslateClient(const std::string& svr_ip, uint16_t svr_port)
        : latch_(1)
        , client_(loopthread_.startLoop(), muduo::net::InetAddress(svr_ip, svr_port), "TranslateClient")
    {
        client_.setConnectionCallback(
            std::bind(&TranslateClient::onConnection, this, std::placeholders::_1)
        );
        client_.setMessageCallback(
            std::bind(&TranslateClient::onMessage, this, std::placeholders::_1, 
                std::placeholders::_2, std::placeholders::_3)
        );
    }  
    void connect()     // 连接服务器
    {
        client_.connect();      // 非阻塞接口
        latch_.wait();          // 连接时进行阻塞，连接成功回调函数唤醒
    }
    bool send(const std::string& msg)
    {
        if(conn_->connected() == false) return false;
        conn_->send(msg);
        return true;
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected() == true) {
            latch_.countDown();     // 唤醒主线程连接时的阻塞
            conn_ = conn;          
        } 
        else conn_.reset();     // 关闭连接(shared_ptr 内部成员方法)
    }
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buffer, muduo::Timestamp)
    {
        std::cout << buffer->retrieveAllAsString() << "\n";
    }
private:
    muduo::net::EventLoopThread loopthread_;
    muduo::net::TcpClient client_;
    muduo::CountDownLatch latch_;
    muduo::net::TcpConnectionPtr conn_;
};

int main()
{
    TranslateClient client("127.0.0.1", 8888);
    client.connect();

    std::string msg;
    while (true)
    {
        std::cin >> msg;
        client.send(msg);
    }

    return 0;
}